<template>
	<view class="community-container"> 
		<!-- 分类标签 -->
		<view class="category-tabs">
			<scroll-view scroll-x enable-flex class="category-scroll" show-scrollbar="false">
				<view v-for="(category, index) in categories" :key="index"
					:class="['category-tab', currentCategory === index ? 'active' : '']"
					@tap="switchCategory(index)">
					{{ category.name }}
				</view>
			</scroll-view>
		</view>

		<!-- 动态列表 -->
		<scroll-view class="feed-list" 
			:refresher-enabled="true" 
			:refresher-triggered="refreshing"
			@refresherpulling="onPulling"
			@refresherrefresh="onRefresh"
			@scrolltolower="onLoadMore"
			lower-threshold="200">

			<!-- 动态卡片 -->
			<view v-for="(post, index) in posts" :key="index" class="post-card">
				<!-- 创作者信息 -->
				<view class="author-info" @tap="navigateToProfile(post.author.id)">
					<image :src="post.author.avatar" class="author-avatar" mode="aspectFill" />
					<view class="author-details">
						<view class="author-name-wrapper">
							<text class="author-name">{{ post.author.name }}</text>
							<image v-if="post.author.verified" src="/static/tabbar/sq_.png" class="verified-badge" mode="aspectFit" />
						</view>
						<text class="post-time">{{ formatRelativeTime(post.time) }}</text>
					</view>
				</view>

			<!-- 动态内容 -->
			<view class="post-content" @tap="expandContent(index)" v-if="post.content.text">
				<text class="post-text" :class="{ 'expanded': post.expanded }">
					{{ post.expanded ? post.content.text : truncateText(post.content.text, 100) }}
				</text>
				<text v-if="post.content.text.length > 100" class="expand-link">
					{{ post.expanded ? 'Show less' : 'Show more' }}
				</text>
			</view>

			<!-- 图片内容 -->
			<view v-if="post.content.images && post.content.images.length > 0" class="post-images">
				<view :class="getImageGridClass(post.content.images.length)" @tap="previewImages(post.content.images, $event)">
					<image v-for="(img, imgIndex) in post.content.images" :key="imgIndex"
						:src="img" :class="getImageClass(post.content.images.length, imgIndex)" mode="aspectFill" />
				</view>
			</view>

			<!-- 视频内容 -->
			<view v-if="post.content.video" class="post-video" @tap="playVideo(post.content.video)">
				<image :src="post.content.video.cover" class="video-cover" mode="aspectFill" />
				<view class="video-play-icon">
					<uni-icons type="play-circle-filled" size="64" color="#fff" />
				</view>
				<view class="video-duration" v-if="post.content.video.duration">
					{{ formatDuration(post.content.video.duration) }}
				</view>
			</view>

			<!-- 互动区域 -->
			<view class="post-interactions">
				<view class="interaction-item" @tap="toggleLike(post.id)">
					<uni-icons :type="post.liked ? 'heart-filled' : 'heart'" 
						:color="post.liked ? '#FE2B54' : '#666'" size="20" />
					<view :class="{ 'liked': post.liked }" class="interaction-text">{{ formatCount(post.likes) }}</view>
				</view>
				<view class="interaction-item" @tap="navigateToComments(post.id)">
					<uni-icons type="chatbubble" color="#666" size="20" />
					<view class="interaction-text">{{ formatCount(post.comments) }}</view>
				</view>
				<!-- <view class="interaction-item" @tap="sharePost(post.id)">
					<uni-icons type="share" color="#666" size="28" />
					<text class="interaction-text">{{ formatCount(post.shares) }}</text>
				</view> -->
			</view>
			</view>

			<!-- 加载更多 -->
			<view v-if="loading" class="loading-more">
				<uni-icons type="spinner-cycle" size="24" color="#666" />
				<text class="loading-text">Loading...</text>
			</view>

			<!-- 无更多内容 -->
			<view v-if="!hasMore && posts.length > 0" class="no-more">
				<text>No more content</text>
			</view>

			<!-- 空状态 -->
			<view v-if="!loading && posts.length === 0" class="empty-state">
				<uni-icons type="chatboxes" size="80" color="#666" />
				<text class="empty-text">No community content</text>
				<text class="empty-tip">Pull down to refresh</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			// 分类标签
			categories: [
				{ name: 'All' },
				{ name: 'Recommended' },
				{ name: 'Following' }
			],
			currentCategory: 0,
			
			// 动态数据
			posts: [],
			
			// 加载状态
			refreshing: false,
			loading: false,
			hasMore: true,
			page: 1
		}
	},

	onLoad() {
		// 初始化加载数据
		this.loadPosts();
	},

	methods: {
		// 切换分类
		switchCategory(index) {
			if (this.currentCategory === index) return;
			this.currentCategory = index;
			this.page = 1;
			this.posts = [];
			this.hasMore = true;
			this.loadPosts();
		},

		// 加载帖子数据
		loadPosts() {
			this.loading = true;
			
			// 模拟网络请求
			setTimeout(() => {
				this.generateMockPosts();
				this.loading = false;
			}, 500);
		},

		// 生成模拟数据
		generateMockPosts() {
			const mockPosts = [
				{
					id: Date.now() + 1,
					author: {
						id: 1,
						name: 'Mars Explorer',
						avatar: '/static/hot/1.png',
						verified: true
					},
					time: Date.now() - 3600000,
					content: {
						text: 'Sharing a set of high-definition photos of Mars surface today, these are our latest exploration results. The Martian landscape is truly amazing, especially those huge canyons and craters. Do you think there was ever life on Mars?',
						images: ['/static/hot/1.png', '/static/hot/2.png', '/static/hot/3.png']
					},
					likes: 128,
					comments: 42,
					shares: 16,
					liked: false,
					expanded: false
				},
				{
					id: Date.now() + 2,
					author: {
						id: 2,
						name: 'Space Traveler',
						avatar: '/static/hot/4.png',
						verified: false
					},
					time: Date.now() - 7200000,
					content: {
						text: 'Just completed a virtual Mars walk! It feels like standing on Mars surface for real. A fun fact: A day on Mars is about 39 minutes and 35 seconds longer than on Earth.',
						video: {
							url: '/static/video/1.mov',
							cover: '/static/hot/4.png',
							duration: '01:45'
						}
					},
					likes: 89,
					comments: 23,
					shares: 9,
					liked: true,
					expanded: false
				},
				{
					id: Date.now() + 3,
					author: {
						id: 3,
						name: 'Space Scientist',
						avatar: '/static/hot/5.png',
						verified: true
					},
					time: Date.now() - 10800000,
					content: {
						text: 'Recent research suggests that there may be liquid water lakes beneath Mars south polar ice cap! This discovery is crucial for finding life on Mars. Our team is analyzing this data and will share more details later.',
						images: ['/static/hot/5.png', '/static/hot/6.jpg']
					},
					likes: 256,
					comments: 78,
					shares: 42,
					liked: false,
					expanded: false
				},
				{
					id: Date.now() + 4,
					author: {
						id: 4,
						name: 'Mars Enthusiast',
						avatar: '/static/hot/6.jpg',
						verified: false
					},
					time: Date.now() - 18000000,
					content: {
						text: 'Text-only sharing: I have been curious about Mars since I was a child and hope to become a real Mars explorer one day. Do you have any interesting questions about Mars? I would be happy to discuss them!',
						images: []
					},
					likes: 45,
					comments: 18,
					shares: 5,
					liked: false,
					expanded: false
				}
			];

			if (this.page === 1) {
				this.posts = mockPosts;
			} else {
				this.posts = [...this.posts, ...mockPosts];
			}

			// 模拟没有更多数据
			if (this.page > 3) {
				this.hasMore = false;
			}
		},

		// 格式化相对时间
		formatRelativeTime(timestamp) {
			const now = Date.now();
			const diff = now - timestamp;
			const minutes = Math.floor(diff / 60000);
			const hours = Math.floor(diff / 3600000);
			const days = Math.floor(diff / 86400000);

			if (minutes < 1) return 'Just now';
			if (minutes < 60) return `${minutes}m ago`;
			if (hours < 24) return `${hours}h ago`;
			if (days < 7) return `${days}d ago`;
			return new Date(timestamp).toLocaleDateString();
		},

		// 格式化数字
		formatCount(count) {
			if (count >= 10000) {
				return (count / 10000).toFixed(1) + 'w';
			}
			if (count >= 1000) {
				return (count / 1000).toFixed(1) + 'k';
			}
			return count;
		},

		// 格式化视频时长
		formatDuration(duration) {
			return duration;
		},

		// 截断文本
		truncateText(text, maxLength) {
			if (text.length <= maxLength) return text;
			return text.substring(0, maxLength) + '...';
		},

		// 展开/收起内容
		expandContent(index) {
			this.posts[index].expanded = !this.posts[index].expanded;
		},

		// 获取图片网格样式
		getImageGridClass(imageCount) {
			if (imageCount === 1) return 'image-grid single';
			if (imageCount === 2 || imageCount === 4) return 'image-grid double';
			return 'image-grid triple';
		},

		// 获取图片样式
		getImageClass(imageCount, index) {
			return {
				'post-image': true,
				'single-image': imageCount === 1,
				'double-image': imageCount === 2 || imageCount === 4,
				'triple-image': imageCount >= 3
			};
		},

		// 点赞/取消点赞
		toggleLike(postId) {
			const post = this.posts.find(p => p.id === postId);
			if (post) {
				post.liked = !post.liked;
				post.likes += post.liked ? 1 : -1;
			}
		},

		// 预览图片
		previewImages(images, event) {
			// 获取点击的图片索引
			const imgElements = event.currentTarget.querySelectorAll('image');
			let index = 0;
			for (let i = 0; i < imgElements.length; i++) {
				if (imgElements[i] === event.target) {
					index = i;
					break;
				}
			}

			uni.previewImage({
				urls: images,
				current: index
			});
		},

		// 播放视频
		playVideo(video) {
			uni.playVideo({
				url: video.url,
				showCenterPlayBtn: true,
				autoplay: true
			});
		},

		// 跳转到个人主页
		navigateToProfile(authorId) {
			// 这里应该跳转到创作者主页，目前先提示
			uni.showToast({
				title: `View creator ${authorId}'s profile`,
				icon: 'none'
			});
		},

		// 跳转到评论页
		navigateToComments(postId) {
			// 这里应该跳转到评论详情页，目前先提示
			uni.showToast({
				title: `View post ${postId}'s comments`,
				icon: 'none'
			});
		},

		// 分享帖子
		sharePost(postId) {
			uni.showActionSheet({
				itemList: ['Share to WeChat', 'Share to QQ', 'Share to Weibo'],
				success: (res) => {
					// 模拟分享成功
					const post = this.posts.find(p => p.id === postId);
					if (post) {
						post.shares++;
					}
					uni.showToast({
						title: 'Shared successfully',
						icon: 'success'
					});
				}
			});
		},

		// 下拉刷新相关方法
		onPulling() {
			// 下拉中，可以添加一些自定义动画
		},

		onRefresh() {
			this.refreshing = true;
			this.page = 1;
			this.hasMore = true;
			
			// 模拟刷新数据
			setTimeout(() => {
				this.generateMockPosts();
				this.refreshing = false;
			}, 1000);
		},

		// 加载更多
		onLoadMore() {
			if (this.loading || !this.hasMore) return;
			
			this.page++;
			this.loadPosts();
		}
	}
}
</script>

<style lang="scss" scoped>
.community-container {
	background: #121212;
	min-height: 100vh;
	color: #fff;
}

/* 顶部导航栏 */
.nav-header {
	height: 92rpx;
	background: #1e1e1e;
	display: flex;
	align-items: center;
	justify-content: center;
	border-bottom: 1rpx solid #333;
	position: sticky;
	top: 0;
	z-index: 10;

	.nav-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #fff;
	}
}

/* 分类标签 */
.category-tabs {
	background: #1e1e1e;
	margin-bottom: 20rpx;

	.category-scroll {
		padding: 0 32rpx;
		white-space: nowrap;

		.category-tab {
			display: inline-flex;
			align-items: center;
			justify-content: center;
			padding: 24rpx 32rpx;
			font-size: 32rpx;
			color: #999;
			position: relative;
			line-height: 1.2;

			&.active {
				color: #FE2B54;
				font-weight: 500;

				&::after {
					content: '';
					position: absolute;
					bottom: 16rpx;
					left: 50%;
					transform: translateX(-50%);
					width: 40rpx;
					height: 6rpx;
					background: #FE2B54;
					border-radius: 3rpx;
				}
			}
		}
	}
}

/* 动态列表 */
.feed-list {
	min-height: calc(100vh - 184rpx);
}

/* 动态卡片 */
.post-card {
	background: #1e1e1e;
	padding: 32rpx;
	margin-bottom: 20rpx;
}

/* 创作者信息 */
.author-info {
	display: flex;
	align-items: center;
	margin-bottom: 24rpx;

	.author-avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		margin-right: 20rpx;
	}

	.author-details {
		flex: 1;

		.author-name-wrapper {
			display: flex;
			align-items: center;

			.author-name {
				font-size: 32rpx;
				font-weight: 500;
				color: #fff;
				margin-right: 8rpx;
			}

			.verified-badge {
				width: 32rpx;
				height: 32rpx;
			}
		}

		.post-time {
			font-size: 24rpx;
			color: #666;
			margin-top: 4rpx;
		}
	}
}

/* 动态内容 */
.post-content {
	margin-bottom: 24rpx;

	.post-text {
		font-size: 32rpx;
		color: #fff;
		line-height: 1.5;
		word-wrap: break-word;
		overflow: hidden;
		display: -webkit-box;
		-webkit-line-clamp: 3;
		-webkit-box-orient: vertical;

		&.expanded {
			display: block;
		}
	}

	.expand-link {
		font-size: 30rpx;
		color: #FE2B54;
		margin-top: 8rpx;
		display: block;
	}
}

/* 图片内容 */
.post-images {
	margin-bottom: 24rpx;

	.image-grid {
		display: flex;
		flex-wrap: wrap;
		gap: 12rpx;

		&.single {
			.post-image {
				width: 100%;
				height: 400rpx;
			}
		}

		&.double {
			.post-image {
				width: calc(50% - 6rpx);
				height: 280rpx;
			}
		}

		&.triple {
			.post-image {
				width: calc(33.333% - 8rpx);
				height: 200rpx;
			}
		}
	}

	.post-image {
		border-radius: 12rpx;
		overflow: hidden;

		&.single-image {
			aspect-ratio: 16/9;
		}
	}
}

/* 视频内容 */
.post-video {
	position: relative;
	width: 100%;
	height: 400rpx;
	margin-bottom: 24rpx;
	border-radius: 12rpx;
	overflow: hidden;

	.video-cover {
		width: 100%;
		height: 100%;
	}

	.video-play-icon {
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
	}

	.video-duration {
		position: absolute;
		right: 20rpx;
		bottom: 20rpx;
		background: rgba(0, 0, 0, 0.6);
		color: #fff;
		font-size: 24rpx;
		padding: 4rpx 16rpx;
		border-radius: 16rpx;
	}
}

/* 互动区域 */
.post-interactions {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding-top: 24rpx;
	border-top: 1rpx solid #333;

	.interaction-item {
		display: flex;
		align-items: center;
		gap: 8rpx;
		padding: 8rpx 24rpx;

		.interaction-text {
			font-size: 26rpx;
			color: #666;

			&.liked {
				color: #FE2B54;
			}
		}
	}
}

/* 加载状态 */
.loading-more {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 32rpx 0;
	gap: 12rpx;

	.loading-text {
		font-size: 28rpx;
		color: #666;
	}
}

/* 无更多内容 */
.no-more {
	text-align: center;
	padding: 32rpx 0;
	font-size: 28rpx;
	color: #666;
}

/* 空状态 */
.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 160rpx 0;

	.empty-text {
		font-size: 32rpx;
		color: #fff;
		margin: 32rpx 0 16rpx 0;
	}

	.empty-tip {
		font-size: 28rpx;
		color: #666;
	}
}
</style>
